//
//  CardListView.m
//  OurWallet
//
//  Created by 小肥羊 on 16/1/5.
//  Copyright © 2016年 小肥羊. All rights reserved.
//

#import "CardListView.h"
#import "CardCell.h"

NSString *const CardCellIdentifier = @"CardCell";

@implementation CardListView

- (id)initWithFrame:(CGRect)frame
{
    NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:@"CardListView" owner:nil options:nil];
    self = [nibs lastObject];
    if (self) {
        self.frame = frame;
        self.listTableView.delegate = self;
        self.listTableView.dataSource = self;
        self.listTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.listTableView.estimatedRowHeight = 140;
        self.listTableView.rowHeight = UITableViewAutomaticDimension;
        [self.listTableView registerNib:[UINib nibWithNibName:CardCellIdentifier bundle:nil] forCellReuseIdentifier:CardCellIdentifier];
        [self.listTableView.layer setMasksToBounds:NO];
        self.cardArray = [[NSArray alloc] init];
    } else {
        self = [super initWithFrame:frame];
    }
    return self;
}

- (void)setCardArray:(NSArray *)cardArray
{
    _cardArray = cardArray;
    dispatch_async(dispatch_get_main_queue(), ^{
        // 更UI
        [self.listTableView reloadData];
    });
}


#pragma mark - 列表代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _cardArray.count + 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CardCell *cell = [tableView dequeueReusableCellWithIdentifier:CardCellIdentifier];
    cell.cellIndex = indexPath;
    cell.delegate = self.delegate;
    if (indexPath.row < self.cardArray.count) {
        NSDictionary *cardDict = self.cardArray[indexPath.row];
        [cell.cardNameLabel setText:cardDict[@"cardName"]];
        [cell.moneyLabel setText:[cardDict[@"money"] stringValue]];
    } else {
        [cell.cardNameLabel setText:@"激活卡"];
        [cell.moneyLabel setText:@""];
    }
    [tableView sendSubviewToBack:cell];
    return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
//    if (indexPath.row > 0) {
//        NSIndexPath *path = [NSIndexPath indexPathForRow:indexPath.row - 1 inSection:indexPath.section];
//        [tableView insertSubview:cell aboveSubview:[tableView cellForRowAtIndexPath:path]];
//    }
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
